const _ = require('lodash')
const dayjs = require('dayjs')

/**
 * 处理 property 的类型
 *
 * @param {*} property
 * @return {*}
 */
const handlePropertyType = (property) => {
	if (property.type === 'string') {
		return 'string'
	}
	if (property.type === 'enum') {
		return property.enumName
	}

	return property.type + (property.nullable ? '?' : '')
}

/**
 * 处理 映射数据库的语句
 *
 * @param {*} property
 * @return {*}
 */
const handleDbContextModelCreating = (config, property) => {
	let str = `b.Property(x => x.${property.name})`

	// required
	if (!property.required) str += `.IsRequired(false)`

	// max
	if (property.max && property.max > 0) str += `.HasMaxLength(${config.entityName}Consts.Max${property.name}Length)`

	// enum
	if (property.type === 'enum' && property.enumConver) str += `.HasConversion(v => v.ToString(), v => (${property.enumName})Enum.Parse(typeof(${property.enumName}), v)).IsUnicode(false)`

	// ColumnName
	str += `.HasColumnName(nameof(${config.entityName}.${property.name}));`

	return str
}

const translate = (config) => {
	// 添加创建时间
	config._createAt = dayjs().format('YYYY-MM-DD HH:mm:ss')
	config._enumNamespace = ''
	config._lowerEntityName = _.lowerFirst(config.entityName)
	config._lowerNamespace = _.lowerFirst(config.namespace)
	// 遍历 properties
	if (config.properties) {
		_.forEach(config.properties, (item) => {
			// 处理类型
			item._lowerName = _.lowerFirst(item.name)
			item._fullType = handlePropertyType(item)
			item._dbContextModelCreating = handleDbContextModelCreating(config, item)

			if (item.type === 'enum' && item.enumNamespace) config._enumNamespace += `using ${item.enumNamespace};\r\n`
		})
	}

	if (config.baseProperties) {
		_.forEach(config.baseProperties, (item) => {
			// 处理类型
			item._lowerName = _.lowerFirst(item.name)
			item._fullType = handlePropertyType(item)
			item._dbContextModelCreating = handleDbContextModelCreating(config, item)
		})
	}
}

module.exports = {
	translate,
}
